<?php

namespace App\Services\Menu;

use App\Lib\Util\ErrorCode;
use App\Models\Admin\MenuModel;

/**
 * Class RoleService
 * @package App\Services\Admin
 */
class MenuService
{

  private $MenuModel;

  public function __construct(MenuModel $MenuModel)
  {
    $this->MenuModel = $MenuModel;
  }

  /**
   * 获取权限列表(三级)
   * @return array|mixed
   */
  public function getMenuList()
  {
    $arrRoleInfo = $this->MenuModel::query()->where('parent',0)->with(
      [
        'children' => function ($query) {
          $query->select('*')->with(['children'=> function ($query) {
            $query->select('*')->with(['children']);
          }]);
        }
      ]
    )->get();
    if (empty($arrRoleInfo)) {
      throw new \Exception('', ErrorCode::NO_DATA);
    }
    return $arrRoleInfo;
  }

  /**
   * 获取所有权限信息(简版)
   * @return array|mixed
   */
  public function getMenuListOnly()
  {
    $arrRoleInfo = $this->MenuModel::query()->where('parent',0)->select('id','title','parent','hidden','path')->with(
      [
        'children' => function ($query) {
          $query->select('id','title','parent','hidden','path')->with(['children'=> function ($query) {
            $query->select('id','title','parent','hidden','path')->with(['children']);
          }]);
        }
      ]
    )->get();
    if (empty($arrRoleInfo)) {
      throw new \Exception('', ErrorCode::NO_DATA);
    }
    return $arrRoleInfo;
  }

  /**
   * 添加权限信息
   * @param $data
   * @return array
   */
  public function addMenu($data)
  {
    $res = $this->MenuModel::query()->create($data)->toArray();
    return $res;
  }

  /**
   * 更信权限信息
   * @param $data
   * @return int
   */
  public function editMenu($data)
  {
    $update = array();
    $id = $data['key'];
    unset($data['key']);

    if (!empty($data['title'])) {
      $update['title'] = $data['title'];
    }
    if (!empty($data['path'])) {
      $update['path'] = $data['path'];
    }
    if (!empty($data['component'])) {
      $update['component'] = $data['component'];
    }
    if (!empty($data['hidden'])) {
      $update['hidden'] = $data['hidden'];
    }
    if (!empty($data['icon'])) {
      $update['icon'] = $data['icon'];
    }
    if (!empty($data['sort'])) {
      $update['sort'] = $data['sort'];
    }
    return $this->MenuModel::query()->where('id', $id)->update($update);
  }

  /**
   * 删除权限信息
   * @param $id
   * @return mixed
   */
  public function delMenu($id)
  {
    $data = array($id);
    $res = $this->MenuModel::query()->whereIn('id', $data)->delete();
    return $res;
  }

}
